package com.edwin.websitebe.filter;

import cn.hutool.http.ContentType;
import com.alibaba.fastjson2.JSON;
import com.edwin.websitebe.util.TokenUtil;
import com.edwin.websitebe.vo.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.CharSet;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpHeaders;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;

@Slf4j
@WebFilter(filterName = "AuthFilter", urlPatterns = "/*")
public class AuthFilter implements Filter {

    private final List<String> WHITE_LIST = Arrays.asList(
            "/website-api/user/login",
            "/website-api/user/logout",
            "/website-api/news",
            "/website-api/editor/server",
            "/website-api/download",
            "/website-api/api",
            "/website-api/game/richTextUpload",
            "/website-api/member/memberLogin",
            "/website-api/member/memberRegister"
    );

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        servletResponse.setCharacterEncoding("utf-8");
        servletResponse.setContentType(ContentType.build(ContentType.JSON, StandardCharsets.UTF_8));
        String url = request.getRequestURI();
        boolean pass = WHITE_LIST.stream().anyMatch(url::startsWith);
        if (pass) {
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
        String token = request.getHeader(HttpHeaders.AUTHORIZATION);
        if (StringUtils.isNotEmpty(token)) {
            if (TokenUtil.verify(token)) {
                filterChain.doFilter(servletRequest, servletResponse);
            } else {
                servletResponse.getWriter().write(JSON.toJSONString(new ResultVO<Void>().fail("100", "登录状态已过期")));
                servletResponse.getWriter().close();
            }
        } else {
            servletResponse.getWriter().write(JSON.toJSONString(new ResultVO<Void>().fail("100", "未登录")));
            servletResponse.getWriter().close();
        }

    }

}
